import React, { useState, useEffect, useMemo } from 'react'
import {
  Card,
  Row,
  Col,
  Space,
  Button,
  Typography,
  Tag,
  Tooltip,
  Select,
  Switch,
  Divider,
  Alert,
} from 'antd'
import {
  DiffOutlined,
  SwapOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
  CopyOutlined,
  DownloadOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
} from '@ant-design/icons'
import { formatDateTime, copyToClipboard, downloadFile } from '@/utils'
import { Version } from '@/types/version'

const { Text, Title } = Typography
const { Option } = Select

interface VersionCompareProps {
  version1: Version
  version2: Version
  onSwapVersions?: () => void
  onClose?: () => void
  showLineNumbers?: boolean
  showWhitespace?: boolean
  splitView?: boolean
}

interface DiffLine {
  type: 'added' | 'removed' | 'unchanged' | 'modified'
  oldLineNumber?: number
  newLineNumber?: number
  content: string
  oldContent?: string
  newContent?: string
}

const VersionCompare: React.FC<VersionCompareProps> = ({
  version1,
  version2,
  onSwapVersions,
  onClose,
  showLineNumbers = true,
  showWhitespace = false,
  splitView = true,
}) => {
  const [isFullscreen, setIsFullscreen] = useState(false)
  const [viewMode, setViewMode] = useState<'split' | 'unified'>('split')
  const [showOnlyChanges, setShowOnlyChanges] = useState(false)
  const [ignoreWhitespace, setIgnoreWhitespace] = useState(true)

  // 计算差异
  const diffResult = useMemo(() => {
    return calculateDiff(version1.content, version2.content, {
      ignoreWhitespace,
      showWhitespace,
    })
  }, [version1.content, version2.content, ignoreWhitespace, showWhitespace])

  // 过滤显示的行
  const filteredDiff = useMemo(() => {
    if (!showOnlyChanges) return diffResult

    return diffResult.filter(line => line.type !== 'unchanged')
  }, [diffResult, showOnlyChanges])

  // 计算差异的简单实现
  function calculateDiff(
    oldText: string, 
    newText: string, 
    options: { ignoreWhitespace: boolean; showWhitespace: boolean }
  ): DiffLine[] {
    const oldLines = oldText.split('\n')
    const newLines = newText.split('\n')
    const result: DiffLine[] = []

    let oldIndex = 0
    let newIndex = 0

    while (oldIndex < oldLines.length || newIndex < newLines.length) {
      const oldLine = oldLines[oldIndex]
      const newLine = newLines[newIndex]

      if (oldIndex >= oldLines.length) {
        // 只有新行
        result.push({
          type: 'added',
          newLineNumber: newIndex + 1,
          content: newLine,
        })
        newIndex++
      } else if (newIndex >= newLines.length) {
        // 只有旧行
        result.push({
          type: 'removed',
          oldLineNumber: oldIndex + 1,
          content: oldLine,
        })
        oldIndex++
      } else {
        // 比较两行
        const oldLineNormalized = options.ignoreWhitespace ? oldLine.trim() : oldLine
        const newLineNormalized = options.ignoreWhitespace ? newLine.trim() : newLine

        if (oldLineNormalized === newLineNormalized) {
          result.push({
            type: 'unchanged',
            oldLineNumber: oldIndex + 1,
            newLineNumber: newIndex + 1,
            content: oldLine,
          })
        } else {
          // 检查是否是修改
          if (oldLine && newLine) {
            result.push({
              type: 'modified',
              oldLineNumber: oldIndex + 1,
              newLineNumber: newIndex + 1,
              content: newLine,
              oldContent: oldLine,
              newContent: newLine,
            })
          } else if (oldLine) {
            result.push({
              type: 'removed',
              oldLineNumber: oldIndex + 1,
              content: oldLine,
            })
          } else {
            result.push({
              type: 'added',
              newLineNumber: newIndex + 1,
              content: newLine,
            })
          }
        }
        oldIndex++
        newIndex++
      }
    }

    return result
  }

  // 获取差异统计
  const getDiffStats = () => {
    const stats = {
      added: 0,
      removed: 0,
      modified: 0,
      unchanged: 0,
    }

    diffResult.forEach(line => {
      stats[line.type]++
    })

    return stats
  }

  // 复制差异内容
  const handleCopyDiff = async () => {
    const diffText = filteredDiff.map(line => {
      const prefix = line.type === 'added' ? '+' : 
                    line.type === 'removed' ? '-' : 
                    line.type === 'modified' ? '~' : ' '
      return `${prefix} ${line.content}`
    }).join('\n')

    const success = await copyToClipboard(diffText)
    if (success) {
      // message.success('差异内容已复制到剪贴板')
    }
  }

  // 导出差异
  const handleExportDiff = () => {
    const diffText = [
      `版本比较报告`,
      `生成时间: ${new Date().toLocaleString()}`,
      ``,
      `版本1: v${version1.version_number} (${formatDateTime(version1.created_at)})`,
      `版本2: v${version2.version_number} (${formatDateTime(version2.created_at)})`,
      ``,
      `差异统计:`,
      `- 新增行: ${getDiffStats().added}`,
      `- 删除行: ${getDiffStats().removed}`,
      `- 修改行: ${getDiffStats().modified}`,
      `- 未变更行: ${getDiffStats().unchanged}`,
      ``,
      `详细差异:`,
      ``,
      ...filteredDiff.map(line => {
        const prefix = line.type === 'added' ? '+' : 
                      line.type === 'removed' ? '-' : 
                      line.type === 'modified' ? '~' : ' '
        return `${prefix} ${line.content}`
      })
    ].join('\n')

    const blob = new Blob([diffText], { type: 'text/plain;charset=utf-8' })
    downloadFile(blob, `version_diff_${version1.version_number}_${version2.version_number}.txt`)
  }

  // 渲染行号
  const renderLineNumber = (lineNumber?: number) => (
    <div style={{ 
      width: 40, 
      textAlign: 'right', 
      paddingRight: 8,
      color: '#999',
      fontSize: 12,
      fontFamily: 'Monaco, Consolas, monospace',
      userSelect: 'none',
    }}>
      {lineNumber || ''}
    </div>
  )

  // 渲染代码行
  const renderCodeLine = (line: DiffLine) => {
    const getLineStyle = (type: string) => {
      switch (type) {
        case 'added':
          return { backgroundColor: '#f6ffed', borderLeft: '3px solid #52c41a' }
        case 'removed':
          return { backgroundColor: '#fff2f0', borderLeft: '3px solid #ff4d4f' }
        case 'modified':
          return { backgroundColor: '#fff7e6', borderLeft: '3px solid #faad14' }
        default:
          return { backgroundColor: 'transparent' }
      }
    }

    return (
      <div
        style={{
          display: 'flex',
          minHeight: 20,
          fontSize: 12,
          fontFamily: 'Monaco, Consolas, monospace',
          lineHeight: '20px',
          ...getLineStyle(line.type),
        }}
      >
        {showLineNumbers && (
          <>
            {renderLineNumber(line.oldLineNumber)}
            {renderLineNumber(line.newLineNumber)}
          </>
        )}
        <div style={{ 
          flex: 1, 
          paddingLeft: 8,
          paddingRight: 8,
          whiteSpace: 'pre',
          overflow: 'auto',
        }}>
          {line.content}
        </div>
      </div>
    )
  }

  // 渲染分割视图
  const renderSplitView = () => (
    <Row gutter={8}>
      <Col span={12}>
        <Card 
          size="small" 
          title={
            <Space>
              <Text strong>v{version1.version_number}</Text>
              <Text type="secondary">{formatDateTime(version1.created_at)}</Text>
            </Space>
          }
          bodyStyle={{ padding: 0 }}
        >
          <div style={{ maxHeight: 600, overflow: 'auto' }}>
            {filteredDiff.map((line, index) => (
              line.type === 'removed' || line.type === 'unchanged' || line.type === 'modified' ? (
                <div key={index}>
                  {renderCodeLine({
                    ...line,
                    content: line.oldContent || line.content,
                    newLineNumber: undefined,
                  })}
                </div>
              ) : null
            ))}
          </div>
        </Card>
      </Col>
      
      <Col span={12}>
        <Card 
          size="small" 
          title={
            <Space>
              <Text strong>v{version2.version_number}</Text>
              <Text type="secondary">{formatDateTime(version2.created_at)}</Text>
            </Space>
          }
          bodyStyle={{ padding: 0 }}
        >
          <div style={{ maxHeight: 600, overflow: 'auto' }}>
            {filteredDiff.map((line, index) => (
              line.type === 'added' || line.type === 'unchanged' || line.type === 'modified' ? (
                <div key={index}>
                  {renderCodeLine({
                    ...line,
                    content: line.newContent || line.content,
                    oldLineNumber: undefined,
                  })}
                </div>
              ) : null
            ))}
          </div>
        </Card>
      </Col>
    </Row>
  )

  // 渲染统一视图
  const renderUnifiedView = () => (
    <Card 
      size="small" 
      title="版本差异"
      bodyStyle={{ padding: 0 }}
    >
      <div style={{ maxHeight: 600, overflow: 'auto' }}>
        {filteredDiff.map((line, index) => (
          <div key={index}>
            {renderCodeLine(line)}
          </div>
        ))}
      </div>
    </Card>
  )

  const stats = getDiffStats()
  const cardStyle = isFullscreen ? {
    position: 'fixed' as const,
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
    margin: 0,
    borderRadius: 0,
  } : {}

  return (
    <Card 
      style={cardStyle}
      bodyStyle={{ 
        padding: 16,
        height: isFullscreen ? '100vh' : 'auto',
        display: 'flex',
        flexDirection: 'column',
      }}
    >
      {/* 工具栏 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        marginBottom: 16,
        paddingBottom: 12,
        borderBottom: '1px solid #f0f0f0',
      }}>
        <div>
          <Space>
            <DiffOutlined style={{ fontSize: 16 }} />
            <Title level={4} style={{ margin: 0 }}>版本比较</Title>
            <Tag color="blue">v{version1.version_number}</Tag>
            <SwapOutlined />
            <Tag color="green">v{version2.version_number}</Tag>
          </Space>
        </div>

        <Space>
          {/* 视图选项 */}
          <Select
            value={viewMode}
            onChange={setViewMode}
            size="small"
            style={{ width: 100 }}
          >
            <Option value="split">分割视图</Option>
            <Option value="unified">统一视图</Option>
          </Select>

          {/* 显示选项 */}
          <Tooltip title="只显示变更">
            <Switch
              size="small"
              checked={showOnlyChanges}
              onChange={setShowOnlyChanges}
              checkedChildren={<EyeInvisibleOutlined />}
              unCheckedChildren={<EyeOutlined />}
            />
          </Tooltip>

          <Tooltip title="忽略空白字符">
            <Switch
              size="small"
              checked={ignoreWhitespace}
              onChange={setIgnoreWhitespace}
            />
          </Tooltip>

          <Divider type="vertical" />

          {/* 操作按钮 */}
          <Tooltip title="交换版本">
            <Button
              size="small"
              icon={<SwapOutlined />}
              onClick={onSwapVersions}
            />
          </Tooltip>

          <Tooltip title="复制差异">
            <Button
              size="small"
              icon={<CopyOutlined />}
              onClick={handleCopyDiff}
            />
          </Tooltip>

          <Tooltip title="导出差异">
            <Button
              size="small"
              icon={<DownloadOutlined />}
              onClick={handleExportDiff}
            />
          </Tooltip>

          <Tooltip title={isFullscreen ? '退出全屏' : '全屏显示'}>
            <Button
              size="small"
              icon={isFullscreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
              onClick={() => setIsFullscreen(!isFullscreen)}
            />
          </Tooltip>

          {onClose && (
            <Button size="small" onClick={onClose}>
              关闭
            </Button>
          )}
        </Space>
      </div>

      {/* 差异统计 */}
      <Alert
        message={
          <Space>
            <Text>差异统计:</Text>
            <Tag color="success">+{stats.added}</Tag>
            <Tag color="error">-{stats.removed}</Tag>
            <Tag color="warning">~{stats.modified}</Tag>
            <Tag color="default">={stats.unchanged}</Tag>
          </Space>
        }
        type="info"
        showIcon={false}
        style={{ marginBottom: 16 }}
      />

      {/* 差异内容 */}
      <div style={{ flex: 1, overflow: 'hidden' }}>
        {viewMode === 'split' ? renderSplitView() : renderUnifiedView()}
      </div>
    </Card>
  )
}

export default VersionCompare